<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * p卡账户管理管理
 *
 * @icon fa fa-circle-o
 */
class Virtualmachinepcard extends Backend
{
    
    /**
     * Virtualmachinepcard模型对象
     * @var \app\admin\model\Virtualmachinepcard
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Virtualmachinepcard;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
            if($lists){
                foreach ($lists as $k=>$v){
                    $lists[$k]['email'] = '';
                    $lists[$k]['emailpassword'] = '';
                    if (!empty($v['virtualmachine'])) {
                       $account = Db::name('fedition_account')->where('id',$v['virtualmachine'])->find();
                        if (!empty($account)) {
                            $lists[$k]['email'] = $account['email'];
                            $lists[$k]['emailpassword'] = $account['emailpassword'];
                        }
                    }
                }
            }
            $result = array("total" => $list->total(), "rows" => $lists);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                //去重
                $pcard = Db::name('virtualmachine_pcard')->where('name',$params['name'])->find();
                if (!empty($pcard)) {
                    $this->error(__("已有P卡，请重新填写"));
                }
                if ($params['iscustom'] == 1) {
                    if (empty($params['usetime'])) {
                        $this->error(__('P卡使用时间不能为空'));
                    }
                    //如果状态是已使用
                    $accountinfo = Db::name('fedition_account')->where('id',$params['virtualmachine'])->where('status','normal')->where('ispcard',0)->find();
                    if (empty($accountinfo)) {
                        $this->error(__('状态错误,该账户不能绑定P卡'));
                    }
                    $params['status'] = 'normal';
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->auth->id;
                    $params['createtime'] = time();
                    $params['updatetime'] = time();
                    if (!empty($params['usetime'])) {
                        $params['usetime'] = strtotime($params['usetime']);
                    }
                    if (!empty($params['endtime'])) {
                        $params['endtime'] = strtotime($params['endtime']);
                    }
                    $result = $this->model->allowField(true)->insertGetId($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //type 类型 operation具体操作
                    $this->add_pcardlog_log(1,$result,1);
                    if ($params['iscustom'] == 1) {
                        $this->add_pcard($result,$accountinfo);
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                if($row['status'] == 'normal' && $params['status'] == 'notused'){
                    $this->error(__('已使用的P卡不能修改为未使用'));
                }
                if ($row['iscustom'] == 1 && $params['iscustom'] == 0) {
                    $this->error(__('不能回退绑定'));
                }
                if ($params['iscustom'] == 1 && $params['status'] == 'normal') {
                    if (empty($params['usetime'])) {
                        $this->error(__('P卡使用时间不能为空'));
                    }
                    if (!empty($params['virtualmachine'])) {
                        if ($params['virtualmachine'] !== $row['virtualmachine']) {
                            //如果状态是已使用
                            $oldvirtualmachine = $row['virtualmachine'];
                            $accountinfo = Db::name('fedition_account')->where('id',$params['virtualmachine'])->where('status','normal')->where('ispcard',0)->find();
                            if (empty($accountinfo)) {
                                $this->error(__('该账户状态错误不能绑定P卡'));
                            }
                        }
                    } else {
                        $this->error(__('绑定账户不能为空'));
                    }
                }else{
                    unset($params['virtualmachine']);
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if (!empty($params['usetime'])) {
                        $params['usetime'] = strtotime($params['usetime']);
                    }
                    if (!empty($params['endtime'])) {
                        $params['endtime'] = strtotime($params['endtime']);
                    }
                    //判断账户是否已被通过申请
                    $this->add_pcardlog_log(1,$ids,2);
                    if (!empty($accountinfo)) {
                        $this->add_pcard_edit($ids,$accountinfo,$oldvirtualmachine);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function add_pcard($pcard_id,$accountinfo)
    {
        $arr['ispcard'] = 1;
        $arr['pcard_id'] = $pcard_id;
        $account = Db::name('fedition_account')->where('id',$accountinfo['id'])->update($arr);
        $this->add_virtualmachine_log(6,$accountinfo['id'],1);
    }

    public function add_pcard_edit($pcard_id,$accountinfo,$oldid)
    {
        $arr['ispcard'] = 1;
        $arr['pcard_id'] = $pcard_id;
        $account = Db::name('fedition_account')->where('id',$accountinfo['id'])->update($arr);
        $this->add_virtualmachine_log(6,$accountinfo['id'],1);
        if (!empty($oldid)) {
            $arr['ispcard'] = 0;
            $arr['pcard_id'] = 0;
            Db::name('fedition_account')->where('id',$oldid)->update($arr);
            $this->add_virtualmachine_log(6,$oldid,2);
        }
    }
}
